//
//  SWHomeViewController.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/2/26.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit
import SVPullToRefresh
import SVProgressHUD



class SWHomeViewController: SWBasicViewController {

    //MARK: 属性
    private var titleBtn:SWHomeTitleView?
    
    private let pullDownHeight: CGFloat = 44
    
    private let cellIdentifier = "Cell"
    //是否显示更新了多少条的标识
    private var showTipView: Bool?
    
    var statuses: [SWStatus]? {
        didSet{
            //赋值SWStatus的时候刷新界面
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //没登录就不加载
        if SWUserAccountViewModel.sharedInstance.userLogin == false {
            return
        }
        
        SVProgressHUD.showErrorWithStatus("草泥马！")
        
        setUpNavBar()
       
        prepareTableVIew()
        
    }
    
    private func prepareTableVIew() {
        tableView.backgroundColor = UIColor(white: 237 / 255 , alpha: 1)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        //注册cell
        tableView.registerClass(SWStatusCell.self, forCellReuseIdentifier: cellIdentifier)
        
        tableView.estimatedRowHeight = 150
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置refreshControl
        refreshControl = SWRefreshControl()
        refreshControl?.setValue(UIColor.redColor(), forKey: "tintColor")
        //添加事件
        refreshControl?.addTarget(self, action: "loadNewStatus", forControlEvents: UIControlEvents.ValueChanged)
//        //开始刷新
        refreshControl?.beginRefreshing()
//        //主动触发事件
//        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
        //用kvc设置下拉刷新的触发距离
        refreshControl?.setValue(60, forKey: "_snappingHeight")
        //第一次加载微博 ： 一进来先显示以前的
        showTipView = false
        self.loadNewStatus()
        
        //设置上啦加载更多
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.laodMoveStatus()
        }
        
    }
    
    //加载新微博
    func loadNewStatus() {
        
        //最新微博数据
        let since_id = statuses?.first?.id ?? 0
        
        statuesViewModel.loadStatus(since_id, max_id: 0) { (statuses, error) -> () in
            
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                print("获取微博数据失败")
                return
            }
            let count = statuses?.count ?? 0
//            print("加载的的微博\(count)")
            //刷新提示
            if since_id >= 0 && self.showTipView == true {
                self.showPullDownTipView(count)
            }
            
            //没加载到数据
            if count == 0 {
                return
            }
            //之前没有微博
            if since_id == 0 {
                //获取成功
                //            print("获取成功: \(statuses)")
                self.statuses = statuses
            } else { //之前已经有微博 这是刷新
                
                self.statuses = statuses! + self.statuses!
            
            }
            self.showTipView = true
            print("最终的数据\(self.statuses?.count)")
        }
    }
    
    //加载更多
    func laodMoveStatus() {
        //获取到最后的微博id
        let max_id = statuses?.last?.id ?? 0

        statuesViewModel.loadStatus(0, max_id: max_id) { (statuses, error) -> () in
            //让下拉加载动画停止
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil {
                print("加载微博出错")
                return
            }
            //加载更多成功
            let count = statuses?.count ?? 0
            //没有微博
            if count == 0 {
                print("上啦没有加载更多")
                return
            }
            //能获取微博 加到现有的微博后面
            self.statuses = self.statuses! + statuses!
        }
    }
    
    /**
     下拉刷新提示view
     */
    func showPullDownTipView(count: Int) {
        tipViewLabel.text = count == 0 ?  "没有获得新微博" : "更新了\(count)条微博"
        UIView.animateWithDuration(1, animations: { () -> Void in
            // UIView翻转动画(让动画反过来执行)
//                        UIView.setAnimationRepeatAutoreverses(true)
//                        UIView.setAnimationRepeatCount(5)
            //让label下来
            self.tipViewLabel.frame.origin.y = self.pullDownHeight
            }) { (_) -> Void in
               //再来个动画让提示label回去
                UIView.animateWithDuration(1, delay: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                self.tipViewLabel.frame.origin.y = -self.pullDownHeight - 20
                }, completion: nil)
        }
    }
    
    //设置navBarItem
    func setUpNavBar() {
        
        //左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        //titleView
        titleBtn = SWHomeTitleView(title: SWUserAccountViewModel.sharedInstance.userAccount?.screen_name ?? "")
        navigationItem.titleView = titleBtn
        titleBtn!.addTarget(self, action: "titleBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    //titleView按钮点击事件
    func titleBtnClick() {
        
        titleBtn!.selected = !titleBtn!.selected
    
        if titleBtn!.selected {
            
            let popViewVc = SWPopverController()
            popViewVc.view.backgroundColor = UIColor.grayColor()
            //设置弹出样式为Popover
            popViewVc.modalPresentationStyle = UIModalPresentationStyle.Popover
            //设置popover的代理 让popViewVc 呈现菜单模式
            popViewVc.popoverPresentationController?.delegate = self
            popViewVc.popoverPresentationController?.sourceView = navigationItem.titleView
            popViewVc.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            popViewVc.preferredContentSize = CGSize(width: 200, height: 5 * 44 )
            
            
            presentViewController(popViewVc, animated: false, completion: nil)

        }
    }
    //MARK: --懒加载
    lazy var tipViewLabel: UILabel = {
    
        let label = UILabel(textColor: UIColor.whiteColor(), font: 16)
        //设置label的farme
        let point = CGPoint(x: 0, y: -self.pullDownHeight - 20)
        let size = CGSize(width: UIScreen.width, height: self.pullDownHeight)
        label.frame = CGRect(origin: point, size: size)
        //文本居中
        label.textAlignment = NSTextAlignment.Center
        label.backgroundColor = UIColor.orangeColor()
        label.alpha = 0.8
        //放到navbar下面
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
    
    //弹出view
    lazy var statuesViewModel: SWStatusViewModel = SWStatusViewModel()
    



    //MARK: -- 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        print("self.statuses?.count: \(self.statuses?.count)")
        return self.statuses?.count ?? 0
    }
    //设置微博cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SWStatusCell
        
        cell.status = statuses?[indexPath.row]
        
        return cell
    }
    
}
//MARK: -- UIPopoverPresentationControllerDelegate
extension SWHomeViewController : UIPopoverPresentationControllerDelegate {

    //让iphone 上面实现Popover效果
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    //pop关闭时调用
    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
        
        titleBtn!.selected = !titleBtn!.selected
    }
    
}
